package com.thinkingstar.iads.cs.sys.controller;
import java.util.Map;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thinkingstar.iads.cs.sys.enumerate.SUBTYPE;
import com.thinkingstar.iads.cs.sys.enumerate.SYS_USEING_STATUS;
import netscape.javascript.JSObject;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import java.util.HashMap;
import org.nutz.dao.Sqls;
import org.nutz.json.Json;
import java.util.ArrayList;
import org.nutz.dao.sql.Sql;
import org.nutz.lang.Strings;
import org.nutz.dao.sql.Criteria;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import com.thinkingstar.iads.common.config.BaseModule;
import com.thinkingstar.iads.common.config.Globals;
import com.thinkingstar.iads.common.filter.GlobalsFilter;
import com.thinkingstar.iads.common.filter.UserLoginFilter;
import com.thinkingstar.iads.cs.sys.entity.SysResource;
import javax.servlet.http.HttpSession;
import org.nutz.mvc.annotation.Filters;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import javax.servlet.http.HttpServletRequest;
import org.nutz.ioc.loader.annotation.IocBean;
/**
 *
 * 
 */
@IocBean
@At("/private/sys/res")
@Filters({ @By(type = GlobalsFilter.class), @By(type = UserLoginFilter.class) })
public class ResourceModule extends BaseModule {
	@Inject
	protected Dao dao;

	@At("")
	//@Ok("vm:template.private.sys.resource")
	public void user(HttpSession session, HttpServletRequest req) {
	}

	@At
	@Ok("raw")
	public String list(@Param("subtype") int subtype) {
		Criteria cri = Cnd.cri();
		cri.where().and("subtype", "=", subtype);
		cri.getOrderBy().asc("location");
		cri.getOrderBy().asc("id");
		return Json.toJson(daoCtl.list(dao, SysResource.class, cri));
	}

	@At
	@Ok("raw")
	public String getSubtype() {
		List<Object> lists = new ArrayList<>();
		Map<String, Object> so = new HashMap<>();
		for(SUBTYPE s :SUBTYPE.values()){
			so = new HashMap<>();
			so.put("id",s.getId());
			so.put("code",s.getCode());
			lists.add(so);
		}
		return Json.toJson(lists);
	}

	@At("/sysusingstatus")
	@Ok("raw")
	public String getSysUsingStatus() {
		List<Object> lists = new ArrayList<>();
		Map<String, Object> so = new HashMap<>();
		for(SYS_USEING_STATUS s :SYS_USEING_STATUS.values()){
			so = new HashMap<>();
			so.put("id",s.getId());
			so.put("code",s.getCode());
			lists.add(so);
		}
		return Json.toJson(lists);
	}

	
	/**
	 *新增资源时，查询一级和二级菜单
	 *不能新建四级菜单，所以不查三级
	 * */
	@At
	@Ok("raw")
	public String listNew(@Param("subtype") int subtype) {
		Criteria cri = Cnd.cri();
		cri.where().and("subtype", "=", subtype);
		cri.where().and("length(id)", "<", 10);
		cri.getOrderBy().asc("location");
		cri.getOrderBy().asc("id");
		return Json.toJson(daoCtl.list(dao, SysResource.class, cri));
	}
	
	/**
	 * 查询全部
	 * */
	@At
	@Ok("raw")
	public String listAll(@Param("id") String id, @Param("subtype") int subtype) {
		return Json.toJson(getJSON(dao, id, subtype));
	}

	@SuppressWarnings("rawtypes")
	private List getJSON(Dao dao, String id, int subtype) {
		Criteria cri = Cnd.cri();
		if (null == id || "".equals(id)) {
			cri.where().and("id", "like", "____");
		} else {
			cri.where().and("id", "like", id + "____");
		}
		if (subtype >= 0) {
			cri.where().and("subtype", "=", subtype);
		}
		cri.getOrderBy().asc("location");
		cri.getOrderBy().asc("id");
		List<SysResource> list = daoCtl.list(dao, SysResource.class, cri);
        List<Object> array = new ArrayList<Object>();
		for (int i = 0; i < list.size(); i++) {
			SysResource res = list.get(i);
			Map<String,Object> jsonobj = new HashMap<String, Object>();
			String pid = res.getId().substring(0, res.getId().length() - 4);
			if (i == 0 || "".equals(pid))
				pid = "0";
			int num = daoCtl.getRowCount(dao, SysResource.class,
					Cnd.where("id", "like", res.getId() + "____"));
			jsonobj.put("id", res.getId());
			jsonobj.put("name", res.getName());
			jsonobj.put("descript", res.getDescript());
			jsonobj.put("url", res.getUrl());
			jsonobj.put("_parentId", pid);
			String bts = Strings.sNull(res.getButton());
			String[] bt;
			String temp = "";
			if (!"".equals(bts)) {
				bt = StringUtils.split(bts,";");
				for (int j = 0; j < bt.length; j++)
					temp += bt[j].substring(0, bt[j].indexOf("/")) + ";";
			}
			jsonobj.put("bts", temp);
			if (num > 0) {
				jsonobj.put("children", getJSON(dao, res.getId(), subtype));
			}
			array.add(jsonobj);
		}
		return array;
	}

	/***
	 * 修改前查找
	 * */
	@At
    @Ok("raw")
	public SysResource toupdate(@Param("id") String id) {
		return daoCtl.detailByName(dao, SysResource.class, id);
	}

	/****
	 * 修改
	 * */
	@At
	@Ok("raw")
	public String updateSave(@Param("..")NutMap nutMap) {
	    String json_str = nutMap.getString("data");
	    String id = nutMap.getString("id");
        JSONObject jsonObject = (JSONObject) JSONObject.parse(json_str);
		SysResource sysResource = JSON.parseObject(json_str, SysResource.class);
        sysResource.setId(id);
        String pid= nutMap.getString("pid");
        if(pid==null){
			sysResource.setPid("0");
		}

		//	    res.setId(id);
//		res.setButton(res.getButton());
     	return daoCtl.update(dao, sysResource) ? sysResource.getId() : "";
	}

	/****
	 * 新建菜单，查找单位。
	 * */
	@At
	public void toAdd() {
	}

	/***
	 * 新建资源
	 * */
	@At
	@Ok("raw")
	public boolean addSave(@Param("..") SysResource res) {

		Sql sql = Sqls
				.create("select max(location)+1 from dc_sys_resource where id like  @id");
		sql.params().set("id", res.getPid() + "_%");
		int location = daoCtl.getIntRowValue(dao, sql);
		res.setLocation(location);
		res.setId(daoCtl.getSubMenuId(dao, "dc_sys_resource", "id", res.getPid()));
		res.setButton(res.getButton());
		res.setStyle("0");
		return daoCtl.add(dao, res);
	}

	/**
	 * 删除
	 * */
	@At
	@Ok("raw")
	public boolean del(@Param("id") String ids) {
		String[] id = StringUtils.split(ids, ",");
		try{
			for (int i = 0; i < id.length; i++) {
				daoCtl.exeUpdateBySql(
						dao,
						Sqls.create("delete from dc_sys_resource where id like '"
								+ Strings.sNull(id[i]) + "%'"));
				daoCtl.exeUpdateBySql(
						dao,
						Sqls.create("delete from dc_sys_role_resource where resourceid like '"
								+ Strings.sNull(id[i]) + "%'"));
			}
		}catch (Exception e){
            return false;
        }
		return true;
	}

	/**
	 * 转到排序页面
	 * */
	@At
	//@Ok("vm:template.private.sys.resourceSort")
	public void toSort(HttpServletRequest req) {
        List<Object> array = new ArrayList<Object>();
		Criteria cri = Cnd.cri();
		cri.getOrderBy().asc("location");
		cri.getOrderBy().asc("id");
		List<SysResource> list = daoCtl.list(dao, SysResource.class, cri);
		Map<String,Object> jsonroot = new HashMap<String, Object>();
		jsonroot.put("id", "");
		jsonroot.put("pId", "0");
		jsonroot.put("name", "资源列表");
		jsonroot.put("open", true);
		jsonroot.put("childOuter", false);
		jsonroot.put("icon", Globals.APP_BASE_NAME
				+ "/images/icons/icon042a1.gif");
		array.add(jsonroot);
		for (int i = 0; i < list.size(); i++) {
            Map<String,Object> jsonobj = new HashMap<String, Object>();
			SysResource obj = list.get(i);
			jsonobj.put("id", obj.getId());
			String p = obj.getId().substring(0, obj.getId().length() - 4);
			jsonobj.put("pId", p == "" ? "0" : p);
			String name = obj.getName();
			jsonobj.put("name", name);
			jsonobj.put("childOuter", false);
			if (obj.getId().length() < 12) {
				jsonobj.put("open", true);
			} else {
				jsonobj.put("open", false);
			}
			array.add(jsonobj);
		}
		req.setAttribute("str", Json.toJson(array));
	}

	/***
	 * 确认排序
	 * */
	@At
	@Ok("raw")
	public boolean sort(@Param("checkids") String[] checkids) {
        return daoCtl.updateSortRow(dao, "dc_sys_resource", checkids,
				"location", 0);

	}

	@At
	public void resourceButton(){

	}
}
